using B.S.XZYData.Api.Read.Application.Command.Account;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure;
using MediatR;

namespace B.S.XZYData.Api.Read.Application.Handler.Account
{
    /// <summary>
    /// 获取用户选择列表处理器
    /// </summary>
    public class GetAccountForSelectionHandler : IRequestHandler<GetAccountForSelectionCommand, ApiPageing<AccountSelectionDTO>>
    {
        private readonly MyDbContext _dbContext;

        public GetAccountForSelectionHandler(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<ApiPageing<AccountSelectionDTO>> Handle(GetAccountForSelectionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var query = _dbContext.Queryable<AccountModel>()
                    .Where(x => !x.IsDeleted);

                // 应用筛选条件
                if (!string.IsNullOrEmpty(request.Name))
                {
                    query = query.Where(x => x.Name.Contains(request.Name));
                }

                if (!string.IsNullOrEmpty(request.RealName))
                {
                    query = query.Where(x => x.RealName.Contains(request.RealName));
                }

                // 只返回启用的用户
                query = query.Where(x => x.IsState);

                // 获取总数
                var totalCount = await query.CountAsync();

                // 分页查询
                var accounts = await query
                    .OrderByDescending(x => x.CreateTime)
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToListAsync();

                // 映射到DTO
                var accountDtos = accounts.Select(account => new AccountSelectionDTO
                {
                    Id = account.Id,
                    Name = account.Name,
                    RealName = account.RealName,
                    IsState = account.IsState,
                    CreateTime = account.CreateTime
                }).ToList();

                return new ApiPageing<AccountSelectionDTO>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取用户选择列表成功",
                    PageData = accountDtos,
                    TotaCount = totalCount,
                    TotaPage = (int)Math.Ceiling((double)totalCount / request.Size)
                };
            }
            catch (Exception ex)
            {
                return new ApiPageing<AccountSelectionDTO>
                {
                    Code = ApiEnum.Error,
                    Msg = $"获取用户选择列表失败: {ex.Message}",
                    PageData = new List<AccountSelectionDTO>(),
                    TotaCount = 0,
                    TotaPage = (int)Math.Ceiling((double)0 / request.Size)
                };
            }
        }
    }
}
